﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace ORM.NHibernateDemo.Util
{
    public class NHibernateUtil
    {
        public static ISessionFactory CreateSessionFactory()
        {
            var ret = Fluently.Configure()
                .Database(
                    SQLiteConfiguration
                    .Standard
                    .ConnectionString("Data Source=ORM.NHibernateDemo.db;Version=3;BinaryGUID=False;"))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Mapping.PersonMap>())
                .ExposeConfiguration(CreateSchema)
                .BuildSessionFactory();
            return ret;
        }

        public static ISessionFactory CreateSessionFactoryFromXML()
        {
            var conf = new Configuration();
            conf.Configure("./conf/hibernate.cfg.xml");
            conf.AddAssembly(typeof(Models.Person).Assembly);
            var schema = new SchemaExport(conf);
            schema.SetOutputFile("orm.xml.sql");
            schema.Execute(true, true, false);
            return conf.BuildSessionFactory();
        }

        private static void CreateSchema(Configuration cfg)
        {
            var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
            schemaExport.SetOutputFile("001.sql");
            schemaExport.Create(false, true);
        }
    }
}